import cv2

# 创建分类器
face_casecade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')


# 处理函数
def detect(image, scaleFactor=1.05, minNeighbors=2):
    # 图片转为灰度
    gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 对人脸图片进行探测
    face = face_casecade.detectMultiScale(gray_img, scaleFactor=scaleFactor, minNeighbors=minNeighbors)

    # 绘制人脸矩形
    for (x, y, w, h) in face:
        # 在原图上绘制矩形
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    return image


if __name__ == '__main__':
    # 读入图片
    image = cv2.imread("images/face_detection/1.jpg")
    # 显示图片
    cv2.imshow("image", image)
    # 探测人脸
    new_image = detect(image)
    cv2.imshow("detection", new_image)
    # 保存结果
    # cv2.imwrite("images/results/face_detection.jpg", new_image)

    # 键盘上按下q 退出
    while True:
        if cv2.waitKey(100) & 0xff == ord('q'):
            break

    # 释放窗口
    cv2.destroyAllWindows()

